﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Data;
using Meraz.Core.Model;
using Meraz.Core.Repositories;
using Meraz.Core.Parsers;
using Meraz.Core.Managers;
using Ninject;

namespace Meraz.Core.Commands
{
    public interface ICreateUrlsCommand
    {
        List<Url> Execute(IDictionary<string, Domain> urlDomains);
        Url Execute(string url, Domain domain);
    }
    public class CreateUrlsCommand : BaseCommand, ICreateUrlsCommand
    {
        [Inject]
        public CreateUrlsCommand(IUrlRepository urlRepo) { 
            this.UrlRepository = urlRepo ?? new UrlRepository(); 
        }

        public IUrlRepository UrlRepository { get; set; }

        public Url Execute(string url, Domain domain)
        {
            Url oUrl = UrlRepository.Get(url);
            if (oUrl == null)
            {
                oUrl = new Url();
                UrlRepository.Add(oUrl);
                oUrl.Name = url;
                oUrl.Domain = domain;
            }
            
            Commit();
            return oUrl;
        }
        public List<Url> Execute(IDictionary<string, Domain> urlDomains)
        {
            List<Url> urls = new List<Url>();

            foreach (var item in urlDomains)
            {
                Url url = UrlRepository.Get(item.Key);
                if (url == null)
                {
                    url = new Url();
                    UrlRepository.Add(url);
                    url.Name = item.Key;
                    url.Domain = item.Value;
                }
                urls.Add(url);
            } 
            Commit();
            return urls;
        }
    }
}
